<template>
    <el-dialog :title="`${courieritem._id ? '修改' : '新增'}配送员`" v-model="open" width="500px">
        <el-form label-width="auto" :model="courieritem">



            <!-- 图片上传 -->
            <el-form-item label="配送员头像">
                <el-upload class="avatar-uploader"
                 action="http://nocat.life:3011/images/upload"
                    :show-file-list="false" 
                    :on-success="handleAvatarSuccess" 
                    :before-upload="beforeAvatarUpload">
                    <img v-if="courieritem.avatar" 
                    :src="courieritem.avatar" 
                    class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <User />
                    </el-icon>
                </el-upload>
            </el-form-item>













            <el-form-item label="配送员名称">
                <el-input v-model="courieritem.name"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号码">
                <el-input v-model="courieritem.phone"></el-input>
            </el-form-item>

            <el-form-item label="配送员状态">
                <el-radio-group v-model="courieritem.state">

                    <el-radio :value="1">显示</el-radio>
                    <el-radio :value="0">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>

        </el-form>
        <template #footer>
            <el-button type="success" @click="open = false">取消</el-button>
            <el-button type="primary" @click="handleok">确认</el-button>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import api from '../../../api';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
// const imageUrl = ref('')
let emit = defineEmits(['getGroupData'])
//配送员弹窗状态
let open = ref(false)
let courieritem = ref({
    _id: '',
    name: '',
    avatar: '',
    phone: '',
    state: 1,
})


// interface usergroupitem{
//     id:string;
//     name:string;
//     phone:string,
// }
// let groupItem=ref<usergroupitem>({
// id:'',
// name:'',
// phone:'',
// })

//侦听弹窗状态,清空
watch(open, () => {
    if (!open.value) {
        // courieritem.value=; 
        courieritem.value={
            _id: '',
    name: '',
    avatar: '',
    phone: '',
    state: 1,
        }
    }
})






//打开弹窗
let opendialog = (data?: any) => {
    // console.log(data);
    if (data) {
        //进入if,则说明父组件传递了数据（说明当前是在做修改）
        courieritem.value = { ...data };
        //解构赋值，因为修改子组件的内容，父组件内容跟着变，子父组件用的同一个引用地址
        //子组件用的父组件的地址，需要修改引用地址，就要用到解构...
    }
    open.value = true;
}
//子组件需要将方法 opendialog（）暴露出去，父组件才能调用
defineExpose({
    opendialog
})



//弹窗，确认按钮
let handleok = () => {
    if (courieritem.value._id) {
        //判断courieritem是否有值，有值就是在修改，没有值就是在新增
        handleupdate()
      
    } else {
        handleadd()
    }
    open.value=false
}
//新增
let handleadd = () => { 
    console.log('准备新增的配送员数据',courieritem.value);
   let  additem:any={...courieritem.value}
  delete additem._id;
  api.couriers.add(additem)
  .then(res=>{
    console.log(res);
    
  })
}


//修改
let handleupdate = async () => {
    let res = await api.couriers.update({

        ...courieritem.value//解构，更换引用地址

    });
    if (res.code == 200) {
        ElMessage.success('配送员信息修改成功');
        open.value = false;
        emit('getGroupData')
    } else {
        ElMessage.error(res.message)
    }

}




// 头像上传




//图片上传成功后执行的方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,// response响应
//   uploadFile
) => {
    console.log(response);
    if(response.code==200){
courieritem.value.avatar=response.data;
    }
    
//   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
//图片上传前，对图片格式和大小进行验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}




</script>

<style scoped>

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}


</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>